﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace LabMS.Web.OpenProject
{
    public partial class addopenproject : Base.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            strPageUserType.Add("teacher");

            if (!Page.IsPostBack)
            {
                lbAppPerson.Text = UserRealName;
                lbAppDate.Text = DateTime.Now.ToShortDateString();
                bindddl();
                tbTeacherName.Value = UserRealName;
                tbTeacherCode.Value = UserCode;
            }
        }

        void bindddl()
        {
           

            LabMS.BLL.Lab Lab = new LabMS.BLL.Lab();
            List<LabMS.Model.Lab> ParentLab = new List<LabMS.Model.Lab>();
            ParentLab = Lab.GetModelList("Lab_ParentID is null");
            List<LabMS.Model.Lab> SonLab = new List<LabMS.Model.Lab>();
            SonLab = Lab.GetModelList("Lab_ParentID is not null");

            for (int i = 0; i < ParentLab.Count; i++)
            {
                ddlLabName.Items.Add(new ListItem(ParentLab[i].Lab_Name, ParentLab[i].Lab_Code.ToString()));
                for (int j = 0; j < SonLab.Count; j++)
                {
                    if (SonLab[j].Lab_ParentID == ParentLab[i].ID)
                    {
                        ddlLabName.Items.Add(new ListItem("--|" + SonLab[j].Lab_Name, SonLab[j].Lab_Code.ToString()));
                    }
                }
            }

            ExtendBLL.Dictionary eDictionary = new ExtendBLL.Dictionary();
            List<Model.Dictionary> listCClass = new List<LabMS.Model.Dictionary>();


            listCClass = eDictionary.GetItemListByDClass("shiyanleibie");
            ddlProjectCategory.DataSource = listCClass;
            ddlProjectCategory.DataTextField = "Name";
            ddlProjectCategory.DataValueField = "Code";
            ddlProjectCategory.DataBind();

            listCClass = eDictionary.GetItemListByDClass("shiyanleixing");
            ddlProjectType.DataSource = listCClass;
            ddlProjectType.DataTextField = "Name";
            ddlProjectType.DataValueField = "Code";
            ddlProjectType.DataBind();

            listCClass = eDictionary.GetItemListByDClass("shiyanyaoqiu");
            ddlProjectRequire.DataSource = listCClass;
            ddlProjectRequire.DataTextField = "Name";
            ddlProjectRequire.DataValueField = "Code";
            ddlProjectRequire.DataBind();

            listCClass = eDictionary.GetItemListByDClass("shiyanzheleibie");
            ddlProjectPartnerType.DataSource = listCClass;
            ddlProjectPartnerType.DataTextField = "Name";
            ddlProjectPartnerType.DataValueField = "Code";
            ddlProjectPartnerType.DataBind();

            listCClass = eDictionary.GetItemListByDClass("shiyanxiangmulaiyuan");
            ddlProjectComFrom.DataSource = listCClass;
            ddlProjectComFrom.DataTextField = "Name";
            ddlProjectComFrom.DataValueField = "Code";
            ddlProjectComFrom.DataBind();

            LabMS.Model.SysSetting msys = new LabMS.Model.SysSetting();
            ExtendBLL.SysSetting extendsys = new ExtendBLL.SysSetting();
            msys = extendsys.GetCurrentSetting();
            List<string> listYear = Common.GradeHelper.GetCurrentGrade((int)msys.CurrentYear, (int)msys.CurrentSemester, false);
            ddlOPGrade.DataSource = listYear;
            ddlOPGrade.DataBind();
            ddlOPGrade.Items.Insert(0, new ListItem("", "0"));

        }

        protected void bnSave_Click(object sender, EventArgs e)
        {

            LabMS.BLL.OpentProject boproject = new LabMS.BLL.OpentProject();
            LabMS.Model.OpentProject moproject = new LabMS.Model.OpentProject();
            lbErr.Visible = false;
            #region 验证
            if (string.IsNullOrEmpty(tbProjectName.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验项目名称不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(tbProjectCode.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验项目编号不能为空!");
                return;
            }

            List<LabMS.Model.OpentProject> listmoproject = new List<LabMS.Model.OpentProject>();


            listmoproject = boproject.GetModelList("OP_ProjectCode = '" + tbProjectCode.Text + "'");
            if (listmoproject.Count > 0)
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验项目编号已存在!");
                return;
            }
            if (string.IsNullOrEmpty(tbProjectStartWeek.Text.Trim()) || string.IsNullOrEmpty(tbProjectEndWeek.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次不能为空!");
                return;
            }

            int iStartWeek = 0;
            int iEndWeek = 0;

            if (!(int.TryParse(tbProjectStartWeek.Text.Trim(), out iStartWeek) && int.TryParse(tbProjectEndWeek.Text.Trim(), out iEndWeek)))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次只能输入数字!");
                return;
            }
            if (iStartWeek > iEndWeek)
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次开始时间大于结束时间!");
                return;
            }
            if (iStartWeek > 20 || iEndWeek > 20)
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验周次过大!");
                return;
            }

            if (string.IsNullOrEmpty(tbTeacherCode.Value.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "指导老师不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(tb_StudentIDs.Value.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "实验学生不能为空!");
                return;
            }
            #endregion

            moproject.OP_ProjectName = tbProjectName.Text.Trim();
            moproject.OP_ProjectCode = tbProjectCode.Text.Trim();
            moproject.Project_Category = ddlProjectCategory.SelectedValue;
            moproject.Project_EndWeek = iEndWeek;
            moproject.Project_Lab = ddlLabName.SelectedValue;
            moproject.Project_PartnerType = ddlProjectPartnerType.SelectedValue;
            moproject.Project_Require = ddlProjectRequire.SelectedValue;
            moproject.Project_StartWeek = iStartWeek;
            moproject.Project_Subject = tbProjectSubjectCode.Value;
            moproject.Project_Type = ddlProjectType.SelectedValue;
            
            moproject.OP_AppIntro = tbOPReason.Text.Trim();
            moproject.OP_ProSource = ddlProjectComFrom.SelectedValue;
            moproject.OP_Professioanl = tbOPProfessioanl.Text.Trim();
            moproject.OP_PlanningCourseTime = tbOPPlanningCourseTime.Text.Trim();
            moproject.OP_Phone = tbOPPhone.Text.Trim();
            moproject.OP_InCharge = tbOPInCharge.Text.Trim();
            moproject.OP_Grade = ddlOPGrade.SelectedValue;
            moproject.OP_AppIntro = tbOPContent.Text.Trim();
            moproject.OP_Teacher = tbTeacherCode.Value.Trim();
            moproject.OP_OpenType = tbOPContent.Text.Trim();//实验内容

            LabMS.Model.SysSetting msys = new LabMS.Model.SysSetting();
            ExtendBLL.SysSetting extendsys = new ExtendBLL.SysSetting();
            msys = extendsys.GetCurrentSetting();
            moproject.SYear = msys.CurrentYear;
            moproject.Semester = msys.CurrentSemester;

            string strAlertContent = "保存成功!";
            moproject.OP_Audit = "0";
            if (((Button)sender).ID == "btnApp")
            {
                strAlertContent = "申请成功!";
                moproject.OP_Audit = "1";
            }
            moproject.OP_AppTime = DateTime.Now;
            moproject.OP_Applicant = lbAppPerson.Text;
            int iOpenProjectID = 0;
            ////添加文件
            int Attach_ID = AttachmentSave();
            try
            {
                if (Attach_ID != 0) 
                {
                    moproject.Attachment = Attach_ID;
                }
                iOpenProjectID = boproject.Add(moproject);
            }
            catch(Exception ex)
            {
                lbErr.Visible = true;
                lbErr.Text = ex.Message;
                return;
            }
            String [] listsID = tb_StudentIDs.Value.Split(',');


            

            for (int i = 0; i < listsID.Length; ++i)
            {
                LabMS.Model.ProjectAppointment projectapp = new LabMS.Model.ProjectAppointment();
                ExtendBLL.ProjectAppointment bprojectapp = new ExtendBLL.ProjectAppointment();
                projectapp.Appoint_ClassID = "0";
                projectapp.Appoint_ProID = 0;
                projectapp.OP_Appoint_ID = listsID[i].ToString();
                projectapp.OP_ProjectCode = moproject.OP_ProjectCode;
                projectapp.OP_Score = "";
                
                try
                {
                    bprojectapp.Add(projectapp);
                }
                catch (Exception ex)
                {
                    lbErr.Visible = true;
                    lbErr.Text = ex.Message;
                    bprojectapp.Del(" where OP_ProjectCode ='" + moproject.OP_ProjectCode + "'");
                    boproject.Delete(iOpenProjectID);
                    return;
                }
            }

            Common.JShelper.JSAlertAndRedirect(Page, "success", strAlertContent, "currentopenprojectlist.aspx");
        }

        /// <summary>
        /// 返回一个AttachmentID
        /// </summary>
        /// <param></param>
        /// <returns></returns>
        protected int AttachmentSave() 
        {
            int Attach_ID = 0;
            bool saved=false;
            if (HttpContext.Current.Request.Files.Count - 1 > 0) 
            {
                try
                {
                    int count = HttpContext.Current.Request.Files.Count;
                    HttpFileCollection Files = HttpContext.Current.Request.Files;
                    string savePath = HttpContext.Current.Request.MapPath(@"../Content/UpLoadFile/");
                    List<string> fileName = LabMS.Common.FileUpload.SaveFiles(Files, savePath);
                    LabMS.BLL.Attachment Attachment = new LabMS.BLL.Attachment();
                    LabMS.Model.Attachment attachmentmodel = new LabMS.Model.Attachment();
                    Attach_ID = Attachment.Add(attachmentmodel);

                    if (Attach_ID != 0)
                    {
                        LabMS.BLL.AttachmentItem AttachItem = new LabMS.BLL.AttachmentItem();
                        LabMS.Model.AttachmentItem attachmentitemmodel;
                        for (int n = 0; n < fileName.Count; n++)
                        {
                            if (fileName[n].Trim() != "")
                            {
                                attachmentitemmodel = new LabMS.Model.AttachmentItem();
                                attachmentitemmodel.Attach_ID = Attach_ID;
                                attachmentitemmodel.Item_Address = "Content/UpLoadFile/" + fileName[n].Trim();
                                attachmentitemmodel.Item_Name = fileName[n].Substring(0, fileName[0].LastIndexOf("_"));
                                attachmentitemmodel.Item_Type = "3";
                                AttachItem.Add(attachmentitemmodel);
                            }
                        }
                    }
                    saved = true;
                }
                catch (Exception ex)
                {
                    lbErr.Text = ex.Message;
                }
                finally 
                {
                    if (saved == false) 
                    {

                    }
                }
            }
            return Attach_ID;

            
        }

    }
}
